<?php #//v.3.3.0
///////////////////////////////////////////////////////
// COPYRIGHT 2007 Phpauction.org ALL RIGHTS RESERVED //
///////////////////////////////////////////////////////


$TIME = mktime(date("H")+$SETTINGS['timecorrection'],date("i"),date("s"),date("m"), date("d"),date("Y"));
$NOW = date("YmdHis",$TIME);
$NOWB = date("Ymd",$TIME);

if(!isset($_SERVER['SCRIPT_NAME'])) $_SERVER['SCRIPT_NAME'] = 'cron.php';
include "./includes/config.inc.php";
include $include_path."auction_types.inc.php";
include $include_path."converter.inc.php";
include $include_path."dates.inc.php";



function openLogFile () {
	global $logFileHandle, $logFileName;
	global $cronScriptHTMLOutput;

	$logFileHandle = @fopen ($logFileName, "a");
	if ($cronScriptHTMLOutput == true)
		print "<PRE>\n";
}

function closeLogFile () {
	global $logFileHandle;
	global $cronScriptHTMLOutput;

	if ($logFileHandle)
		fclose ($logFileHandle);
	if ($cronScriptHTMLOutput)
		print "</PRE>\n";
}

function printLog ($str) {
	global $logFileHandle;
	global $cronScriptHTMLOutput;

	if ($logFileHandle) {
		if (substr($str, strlen($str)-1, 1) != "\n")
			$str .= "\n";
		fwrite ($logFileHandle, $str);
		if ($cronScriptHTMLOutput)
			print "" . $str;
	}
}

function printLogL ($str, $level) {
	for($i = 1;$i <= $level;++$i)
		$str = "\t" . $str;
	printLog($str);
}

function errorLog ($str) {
	global $logFileHandle, $adminEmail;

	printLog ($str);
	/**
	* mail (
	* $adminEmail,
	* "An cron script error has occured",
	* $str,
	* "From: $adminEmail\n".
	* "Content-type: text/plain\n"
	* );
	*/
	closeLogFile();
	  mysql_close($linktodatabase);
	exit;
}

function errorLogSQL () {
	global $query;
	errorLog ("SQL query error: $query\n" . "Error: " . mysql_error());
}

function constructCategories() {
	$query = "SELECT cat_id, parent_id, sub_counter, counter
	         FROM PHPAUCTIONXL_categories ORDER BY cat_id";
	$res = mysql_query($query);
	while ($row = mysql_fetch_array($res)) {
		$row['updated']=false;
		$categories[$row['cat_id']]=$row;
	}
	return $categories;
}

// initialize cron script
openLogFile();
printLog("=============== STARTING CRON SCRIPT: " . date("F d, Y H:i:s"));

$categories=constructCategories();

/**
* ------------------------------------------------------------
* 1) "close" expired auctions
* closing auction means:
* a) update database:
* + "auctions" table
* + "categories" table - for counters
* + "counters" table
* b) send email to winner (if any) - passing seller's data
* c) send email to seller (reporting if there was a winner)
*/
printLog("++++++ Closing expired auctions");
$TIME = mktime(date("H")+$SETTINGS['timecorrection'],date("i"),date("s"),date("m"), date("d"),date("Y"));
$NOW = date("YmdHis",$TIME);
$NOWB = date("Ymd",$TIME);
$query = "SELECT * FROM PHPAUCTIONXL_auctions
         WHERE ends <='$NOW'
         AND ((closed='0')
         OR (closed='1'
         AND reserve_price > 0
         AND num_bids > 0
         AND current_bid < reserve_price
         AND sold='s'))";
printLog ($query);
$result = mysql_query($query);

if (!$result)
	errorLogSQL();
else {
	$num = mysql_num_rows($result);
	printLog($num . " auctions to close");
	
	$resultAUCTIONS = $result;
	while ($row = mysql_fetch_array($resultAUCTIONS)) {
		$Auction = $row;
		$Auction[description] = strip_tags($Auction[description]);
		printLog("\nProcessing auction: " . $row["id"]);
		// //======================================================
		// BEGINNING OF ITEM WATCH CODE Rida nr 247
		// //======================================================
		// Send notification if user added auction closes
		$ended_auction_id = "$row[id]";
                $title = $row["title"];

		$resultUSERS = mysql_query("SELECT nick,email,item_watch FROM PHPAUCTIONXL_users");
		$num_users = mysql_num_rows($resultUSERS);
		$i = 0;
                $email_sended = array ();
		while ($i < $num_users) {
			$nickname = mysql_result ($resultUSERS, $i, "nick");
			$e_mail = mysql_result ($resultUSERS, $i, "email");
			$keyword = mysql_result ($resultUSERS, $i, "item_watch");
			$key = split(" ", $keyword);
			for ($j = 0; $j < count($key); $j++) {
                              if ( !empty($key[$j]) )
				$match = strpos($key[$j], $ended_auction_id);
			}
			// If keyword matches with opened auction title or/and desc send user a mail
			if ($match && isset($email_sended[$e_mail]) && $email_sended[$e_mail] != 1 ) {
				$sitename = $SETTINGS[sitename];
				$auction_url = $SETTINGS[siteurl] . "item.php?mode=1&id=" . $ended_auction_id;
				// Mail body and mail() functsion
				include (phpa_include("template_item_watch_endedmail_php.html"));
                                $email_sended[$e_mail] = 1;
			}
			$i++;
		}
		//======================================================
		// END OF ITEM WATCH CODE
		//======================================================

		//************************************
		//  update category tables
		//*************************************
		$cat_id = $row["category"];
		$root_cat = $cat_id;
		do {
			// update counter for this category
			$R_parent_id = $categories[$cat_id]['parent_id'];
			$R_cat_id = $categories[$cat_id]['cat_id'];
			$R_counter = intval($categories[$cat_id]['counter']);
			$R_sub_counter = intval($categories[$cat_id]['sub_counter']);
			$R_sub_counter--;
			if ($cat_id == $root_cat)
				--$R_counter;
			if ($R_counter < 0)
				$R_counter = 0;
			if ($R_sub_counter < 0)
				$R_sub_counter = 0;
			$categories[$cat_id]['counter']=$R_counter;
			$categories[$cat_id]['sub_counter']=$R_sub_counter;
			$categories[$cat_id]['updated']=true;
			$cat_id = $R_parent_id;
		} while ($cat_id != 0 && isset($categories[$cat_id]));
		// update "counters" table - decrease number of auctions
		$query = "UPDATE PHPAUCTIONXL_counters SET auctions=(auctions-1),
		         closedauctions=(closedauctions+1)";
		printLogL($query, 1);
		if (!mysql_query($query))
			errorLogSQL();
		// //************************************
		// //  RETRIEVE SELLER INFO FROM DATABASE
		// //*************************************
		$query = "SELECT * FROM PHPAUCTIONXL_users WHERE id='" . $Auction["user"] . "'";
		printLogL($query, 1);
		$result = mysql_query ($query);
		if ($result) {
			if (mysql_num_rows($result) > 0) {
				mysql_data_seek ($result, 0);
				$Seller = mysql_fetch_array($result);
			} else
				$Seller = array();
		} else
			errorLogSQL();
		// //**************************************************
		// // check if there is a winner - and get his info
		// //***************************************************
		$winner_present = false;
		$query = "SELECT * FROM PHPAUCTIONXL_bids WHERE auction='" . $row['id'] . "' ORDER BY bid DESC";
		printLogL($query, 1);
		$result = mysql_query ($query);
		if ($result) {
			if (mysql_num_rows($result) > 0 and ($row['current_bid'] >= $row['reserve_price'] || $row['sold']=='s')) {
				$decrem = mysql_num_rows($result);
				mysql_data_seek($result, 0);
				$WinnerBid = mysql_fetch_array($result);
				$WinnerBid[quantity] = $row[quantity];
				$winner_present = true;
				// //  RETRIEVE WINNER INFO FROM DATABASE
				$query = "SELECT * FROM PHPAUCTIONXL_users WHERE nick='" . $row['current_high_bidder'] . "'";
				$result = mysql_query ($query);
				if ($result) {
					if (mysql_num_rows($result) > 0) {
						mysql_data_seek ($result, 0);
						$Winner = mysql_fetch_array($result);
					} else
						$Winner = array ();
				} else
					errorLogSQL();
			}
		} else
			errorLogSQL();
		/**
		* send email to seller - to notify him
		* create a "report" to seller depending of what kind auction is
		*/
		$atype = intval($Auction["auction_type"]);
		if ($atype == 1) {
			$WINNING_BID = $Auction[current_bid];
			/**
			* Standard auction
			*/
			if ($winner_present) {
        		$report_text = $Winner["nick"] . " (<a href='mailto:".$Winner["email"]."'>". $Winner["email"] . "</a>)\n";
				if($SETTINGS['winner_address'] == 'y'){
					$report_text .= $MSG_30_0086.$Winner['address']." ".$Winner['city']." ".$Winner['zip']." "." ".$Winner['prov'].", ".$Winner['country'];
				}
				// // Add winner's data to "winners" table
				$query = "INSERT INTO PHPAUCTIONXL_winners VALUES (NULL,'" . $Auction['id'] . "','" . $Seller['id'] . "','" . $Winner['id'] . "'," . $Auction['current_bid'] . ",'$NOW',0)";
				$res = @mysql_query($query);
				/**
				* Update column bid in table PHPAUCTIONXL_counters
				*/
				$counterbid = mysql_query("UPDATE PHPAUCTIONXL_counters SET bids=(bids-$decrem)");
			} else {
				$report_text = $MSG_429;
			}
		} else {
			// //**************************************************
			// //  		 Dutch Auction
			// //***************************************************
			unset($WINNERS_NICK);
			unset($WINNERS_EMAIL);
			unset($WINNERS_NAME);
			unset($WINNERS_QUANT);
			unset($WINNERS_BIDQUANT);
			$report_text = "";
			// find out last bids for evey bidder
			$sql = "SELECT max(id) as mid
			       FROM PHPAUCTIONXL_bids
			       WHERE auction =  '" . $Auction['id'] . "' GROUP BY bidder";
			$reint = mysql_query ($sql);
			$iarr = array();
			if ($reint) {
				while ($rwint = mysql_fetch_array($reint))
					$iarr[] = $rwint['mid'];
			}
			// find out winners sorted by bid
			if(count($iarr) > 0) {
				$incl = "(" . join(",", $iarr) . ")";
				$query = "SELECT * FROM PHPAUCTIONXL_bids WHERE id in $incl ORDER BY bid DESC";
				$res = mysql_query ($query);
				if ($res) {
					$numDbids = mysql_num_rows($res);
					/**
					* Update column bid in table PHPAUCTIONXL_counters
					*/
					$counterbid = mysql_query("UPDATE PHPAUCTIONXL_counters SET bids=(bids-$numDbids)");
					if ($numDbids == 0) {
						$report_text = "No bids";
					} else {
						$WINNERS_ID = array();
						$report_text = "";
						$WINNING_BID = $WinnerBid['bid'];
						$items_count = $Auction["quantity"];
						$items_sold = 0;
						$row = mysql_fetch_array($res);
						do {
							if (!in_array($row['bidder'], $WINNERS_ID)) {
								if ($row[bid] < $WINNING_BID) {
									$WINNING_BID = $row[bid];
								}
								$items_wanted = $row["quantity"];
								$items_got = 0;
								if ($items_wanted <= $items_count) {
									$items_got = $items_wanted;
									$items_count -= $items_got;
								} else {
									$items_got = $items_count;
									$items_count -= $items_got;
								}
								$items_sold += $items_got;
								// // Retrieve winner nick from the database
								// // Added by Gianluca Jan. 9, 2002
								$query = "SELECT nick,email,name,address,city,zip,prov,country FROM PHPAUCTIONXL_users WHERE id='$row[bidder]'";
								// print "$query<BR>";
								$res_n = @mysql_query($query);
								$NICK = @mysql_result($res_n, 0, "nick");
								$EMAIL = @mysql_result($res_n, 0, "email");
								$NAME = @mysql_result($res_n, 0, "name");
								$ADDRESS = @mysql_result($res_n, 0, "address")." ".
										@mysql_result($res_n, 0, "city")." ".
										@mysql_result($res_n, 0, "zip")." ".
										@mysql_result($res_n, 0, "prov").", ".
										@mysql_result($res_n, 0, "country");
								$items_got = $items_got;
								// // Addd by Gian - dec 19 2002
								// // ============================
								$WINNERS_ID[$NICK] = $row['bidder'];
								$WINNERS_BID[$NICK] = $row['bid'];
								$WINNERS_NICK[$NICK] = $NICK;
								$WINNERS_EMAIL[$NICK] = $EMAIL;
								$WINNERS_NAME[$NICK] = $NAME;
								$WINNERS_QUANT[$NICK] = $items_got;
								$WINNERS_BIDQUANT[$NICK] = $items_wanted;
								// // ============================
								$report_text .= " $MSG_159 " . $NICK . " ($EMAIL) " . $items_got . " $MSG_5492, $MSG_5493 <#MIN_BID_WIN#> $MSG_5495 - ($MSG_5494 $items_wanted $MSG_5492)<br>";
								if($SETTINGS['winner_address'] == 'y'){
									$report_text .= " ".$MSG_30_0086.$ADDRESS."\n";
								}
								$report_text .= "<br><br>";
								$totalamount = $row[bid];
								// Add winner's data to "winners" table
								$query = "INSERT INTO PHPAUCTIONXL_winners VALUES
								         (NULL,'$Auction[id]','$Seller[id]', '$row[bidder]', $row[bid],'.$NOW.',0)";
								$res_ = @mysql_query($query);
								/**
								* Update column transaction in table PHPAUCTIONXL_counters
								*/
								$counterbid = mysql_query("UPDATE PHPAUCTIONXL_counters SET transactions=(transactions+1)");
							}
							if (!$row = mysql_fetch_array($res)) {
								break;
							}
						} while (($items_count > 0) && $res);

						$report_text .= $MSG_643 . " " . print_money($WINNING_BID);
            $report_text = ereg_replace("<#MIN_BID_WIN#>",print_money($WINNING_BID),$report_text);
            
            /**
						* Added by Marcos U. in order to fix the minimum winner bid as the Winning bid for Dutch Auction. 
						*/
            foreach($WINNERS_BID as $k => $v){
              $WINNERS_BID[$k] = $WINNING_BID;
            }
            $Auction['current_bid'] = $WINNING_BID;
						printLog($report_text);
					}
				} else {
					errorLogSQL();
				}
			}
		}
		printLogL ("mail to seller: " . $Seller["email"], 1);
		$i_title = $Auction["title"];

		$year = substr($Auction['ends'], 0, 4);
		$month = substr($Auction['ends'], 4, 2);
		$day = substr($Auction['ends'], 6, 2);
		$hours = substr($Auction['ends'], 8, 2);
		$minutes = substr($Auction['ends'], 10, 2);
		$ends_string = $month . " " . $day . " " . $year . " " . $hours . ":" . $minutes;

		// // =============== added by Gian for automatic relisting feature
		// // Modified for XL 2.0 to relist only if invoicing is enabled
	
  
    
        /*
  	if ($Auction['relist'] > 0 && ($Auction['relist'] - $Auction['relisted']) > 0) {
			
		//NOTE: Auctomatic relisting
			
			$_BIDSNUM = @mysql_num_rows(@mysql_query("SELECT id FROM PHPAUCTIONXL_bids WHERE auction='" . $Auction['id'] . "'"));

			if ($_BIDSNUM == 0 || ($_BIDSNUM > 0 && $Auction['reserve_price'] > 0 && !$winner_present)) {
				// // Calculate start and end time
				$_STARTS = $NOW;
				$_ENDS = $TIME + $Auction['duration'] * 24 * 60 * 60;
				$_ENDS = date("YmdHis", $_ENDS);

				$close = mysql_query("DELETE PHPAUCTIONXL_bids
				                     where auction='$Auction[id]'");
				$close = mysql_query("DELETE PHPAUCTIONXL_proxybid
				                     where itemid='$Auction[id]'");
				$close = mysql_query("UPDATE PHPAUCTIONXL_auctions SET
				                     starts='$_STARTS',
				                     ends='$_ENDS',
				                     current_bid=0,
				                     num_bids=0,
				                     relisted=relisted+1
				                     where id='$Auction[id]'");
				                     
				                     
				                     
				                     
			} else {
				// // Close auction
				
				
				
				
				
				
				
				$query = "UPDATE PHPAUCTIONXL_auctions SET closed='1',
				         starts='".$Auction[starts]."',
				         ends='".$Auction[ends]."',
				         sold=CASE sold WHEN 's' THEN 'y' ELSE sold END
				         WHERE
				         id=\"$Auction[id]\"";
				if (!mysql_query($query))
					errorLogSQL();
				printLogL($query, 1);
				
				$query = "UPDATE PHPAUCTIONXL_auctions2 SET closed='1'
				         WHERE
				         id=\"$Auction[id]\"";
				if (!mysql_query($query))
					errorLogSQL();
		
				
			}
			
			}
			     */
			     
			if ( $Auction['relist'] > 0 ) {     
			     
$queryrelist="SELECT * FROM PHPAUCTIONXL_auctions WHERE id='".$Auction['id']."'";

  $RELISTEDAUCTION = mysql_fetch_array(@mysql_query($queryrelist));
  
  $_SESSION['RELISTEDAUCTION'] = $RELISTEDAUCTION;
  $RELISTEDAUCTION['id'];
  $sessionVars["SELL_starts"] = date("YmdHis",time()+$SETTINGS['timecorrection']*3600);
          $auctionstarts = $RELISTEDAUCTION['starts'];
          $__STARTS = mktime(substr($auctionstarts, 8, 2), substr($auctionstarts, 10, 2), substr($auctionstarts, 12, 2), substr($auctionstarts, 4, 2), substr($auctionstarts, 6, 2), substr($auctionstarts, 0, 4));
          


  $sessionVars["SELL_title"]         = $RELISTEDAUCTION['title'];
  $sessionVars["SELL_description"]     = $RELISTEDAUCTION['description'];
  $sessionVars["SELL_atype"]         = $RELISTEDAUCTION['auction_type'];
  $sessionVars["SELL_iquantity"]      = $RELISTEDAUCTION['quantity'];
  
  //$sessionVars["SELL_minimum_bid"]     = $RELISTEDAUCTION['minimum_bid'];
  if(doubleval($RELISTEDAUCTION['reserve_price']) > 0)
  {
    $sessionVars["SELL_reserve_price"]   = $RELISTEDAUCTION['reserve_price'];
    $sessionVars["SELL_with_reserve"]  = 'yes';
  }
  else
  {
    $sessionVars["SELL_reserve_price"]   = '';
    $sessionVars["SELL_with_reserve"]  = 'no';
  }
  
  $_SESSION["sellcat"]           = $RELISTEDAUCTION['category'];
  $sessionVars["SELL_sellcat"]      = $RELISTEDAUCTION['category'];
  
  /*
  if(doubleval($RELISTEDAUCTION['buy_now']) > 0)
  {
    $sessionVars["SELL_buy_now_price"]   = $RELISTEDAUCTION['buy_now'];
    $sessionVars["SELL_with_buy_now"]  = 'yes';
  }
  else
  {
    $sessionVars["SELL_buy_now_price"]   = '';
    $sessionVars["SELL_with_buy_now"]  = 'no';
  }
  
  */
  $sessionVars["SELL_duration"]       = $RELISTEDAUCTION['duration'];
  $sessionVars["SELL_relist"]       = $RELISTEDAUCTION['relist'] - 1;
  /* if(doubleval($RELISTEDAUCTION['increment']) > 0)
  {
    $sessionVars["SELL_increment"]       = "2";
    $sessionVars["SELL_customincrement"]   = $RELISTEDAUCTION['increment'];
  }
  else
  {
    $sessionVars["SELL_increment"]       = "1";
    $sessionVars["SELL_customincrement"]   = '';
  }  */
  
  $sessionVars["SELL_customincrement"] 	= doubleval($RELISTEDAUCTION['increment']);
  	$sessionVars["SELL_minimum_bid"] 		= doubleval($RELISTEDAUCTION['minimum_bid']);
  $sessionVars["SELL_country"]       = $RELISTEDAUCTION['location'];
  $sessionVars["SELL_location_zip"]     = $RELISTEDAUCTION['location_zip'];
  $sessionVars["SELL_shipping"]       = $RELISTEDAUCTION['shipping'];
  $sessionVars["SELL_shipping_terms"]    = $RELISTEDAUCTION['shipping_terms'];
  $sessionVars["SELL_payment"]       = $RELISTEDAUCTION['payment'];    
  $sessionVars["SELL_international"]     = $RELISTEDAUCTION['international'];
  $sessionVars["SELL_imgtype"]       = $RELISTEDAUCTION['imgtype'];
  $sessionVars["SELL_file_uploaded"]     = $RELISTEDAUCTION['photo_uploaded'];
  $sessionVars["SELL_pict_url"]       = $RELISTEDAUCTION['pict_url'];
  $sessionVars["SELL_sendemail"]       = $RELISTEDAUCTION['sendemail'];
  $sessionVars["SELL_retail"]= $RELISTEDAUCTION['retail'];
$sessionVars["SELL_shipping_fee"]= $RELISTEDAUCTION['shipping_fee'];
$sessionVars["SELL_return_policy"]= $RELISTEDAUCTION['return_policy'];
    	$sessionVars["SELL_ends"] = $RELISTEDAUCTION['ends'];
       $auctionends = $RELISTEDAUCTION['ends'];
         $__END = mktime(substr($auctionends, 8, 2), substr($auctionends, 10, 2), substr($auctionends, 12, 2), substr($auctionends, 4, 2), substr($auctionends, 6, 2), substr($auctionends, 0, 4));
         $__DIFFERENCE = $__END - $__STARTS;  
         $auctionends2 = date("YmdHis", mktime(substr($auctionends, 8, 2), substr($auctionends, 10, 2), substr($auctionends, 12, 2) + $__DIFFERENCE , substr($auctionends, 4, 2), substr($auctionends, 6, 2), substr($auctionends, 0, 4)));
        $sessionVars["SELL_ends"] = $auctionends;   
         

   $sessionVars["SELL_bids_purchased"]  = $RELISTEDAUCTION['bids_purchased'];
   $sessionVars["SELL_allow_autobidder"] = $RELISTEDAUCTION['allow_autobidder'];
  $sessionVars["SELL_buy_now_switch"] = $RELISTEDAUCTION['buy_now'];
   
        $sessionVars["SELL_bid_credits_reqd"] = $RELISTEDAUCTION['bid_credits_reqd'];
        $sessionVars["SELL_ae_activation"]  = $RELISTEDAUCTION['ae_activation'];
        $sessionVars["SELL_ae_increment"]  = $RELISTEDAUCTION['ae_increment'];
        $sessionVars["SELL_promotion"] = $RELISTEDAUCTION['promotion'];
          $sessionVars["SELL_auction_type2"] = $RELISTEDAUCTION['auction_type2'];
        $sessionVars["SELL_dbl_bidding"] = $RELISTEDAUCTION['dbl_bidding'];
            $sessionVars["SELL_hard_reset"] = $RELISTEDAUCTION['hard_reset'];
                $sessionVars["SELL_notimer"] = $RELISTEDAUCTION['notimer'];
                $sessionVars["SELL_lockout"] = $RELISTEDAUCTION['lockout'];    
			     
			     $queryrelist2 =
    //    "INSERT INTO PHPAUCTIONXL_auctions VALUES ('".$sessionVars["SELL_auction_id"]."', '". // auction id
    "INSERT INTO PHPAUCTIONXL_auctions VALUES (NULL, 
    1, '".
    addslashes($sessionVars["SELL_title"])."', '". // auction title
    $auctionends."', '". // auction starts
    addslashes($sessionVars["SELL_description"])."', '". // auction description
    addslashes($sessionVars["SELL_pict_url"])."', ". // picture URL
    $sessionVars["SELL_sellcat"].", '". // category
    $sessionVars["SELL_minimum_bid"]."', '".// minimum bid
    (($sessionVars["SELL_with_reserve"]=="yes")?$sessionVars["SELL_reserve_price"]:"0")."', '".// reserve price
    $sessionVars["SELL_buy_now_switch"]."', '".
    $sessionVars["SELL_atype"]."', '".// auction type
    $sessionVars["SELL_duration"]."', ".
    doubleval($sessionVars["SELL_customincrement"]).", '".
    $sessionVars["SELL_country"]."', '".// country
    $sessionVars["SELL_location_zip"]."', '".// zip code
    $sessionVars["SELL_shipping"]."', '".// shipping method
    $sessionVars["SELL_payment"]."', '".// payment method$TPL_payments_list
    (($sessionVars["SELL_international"])?"1":"0")."', '".// international shipping
    $auctionends2."', '".// ends
    $sessionVars["SELL_minimum_bid"]."', '".// current bid
    "0', ".// closed
    (($sessionVars["SELL_file_uploaded"])?"1":"0").", ".
    $sessionVars["SELL_iquantity"].", ".// quantity
    "'$SUSPENDED' ".//suspended
    ",'n',
    ".intval($sessionVars["SELL_relist"]).",
    0,
    0,
    'n','". 
    addslashes(strip_tags($sessionVars["SELL_shipping_terms"]))."',
    '".$sessionVars["SELL_buy_now_only"]."',
    '".$sessionVars["SELL_adultonly"]."',
    '---',
    '".$sessionVars["SELL_retail"]."',
    '".$sessionVars["SELL_return_policy"]."',
    '".$sessionVars["SELL_shipping_fee"]."',
    0,
    '".$sessionVars["SELL_promotion"]."',
    '".$sessionVars["SELL_auction_type2"]."', 
    0,
    0,
     '".$sessionVars["SELL_ae_activation"]."',    
'".$sessionVars["SELL_ae_increment"]."',
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
     '".$sessionVars["SELL_bids_purchased"]."',    
'".$sessionVars["SELL_allow_autobidder"]."',  
'".$sessionVars["SELL_bid_credits_reqd"]."', 
'".$sessionVars["SELL_free_seat_bids"]."',
'".$sessionVars["SELL_shipped"]."',
'".$auctionends2."',
'".$sessionVars["SELL_dbl_bidding"]."',
'".$sessionVars["SELL_hard_reset"]."',
'".$sessionVars["SELL_notimer"]."',
0,
'".$sessionVars["SELL_lockout"]."'   
)";
    
    
       
    $resaaa=mysql_query($queryrelist2);
    
        if ($resaaa) {
      $sql="SELECT LAST_INSERT_ID() as id";
      $res_resaaa=mysql_query($sql);
      //      $auction_id=mysql_insert_id();
      $auction_id=mysql_result($res_resaaa,0,"id");
      $_SESSION['sessionVars']['SELL_auction_id']=$auction_id;
      $sessionVars['SELL_auction_id']=$auction_id;
      $TPL_auction_id = $auction_id; 
    } else {
      MySQLError($query);
      exit;
    }          
    
                      $nobidsyet = "No Bids Yet!";
     $queryaa =
    //    "INSERT INTO PHPAUCTIONXL_auctions VALUES ('".$sessionVars["SELL_auction_id"]."', '". // auction id
    "INSERT INTO PHPAUCTIONXL_auctions2 VALUES ('".$TPL_auction_id."',
    '".addslashes($sessionVars["SELL_title"])."', 
    '".$auctionends."', 
    '".addslashes($sessionVars["SELL_pict_url"])."', 
    '".$auctionends2."',
    '"."0"."', 
    '"."0"."',
    '".$sessionVars["SELL_retail"]."',
    '".$auctionends2."','".$nobidsyet."','".$sessionVars["SELL_minimum_bid"]."','".(($sessionVars["SELL_with_reserve"]=="yes")?$sessionVars["SELL_reserve_price"]:"0")."','".doubleval($sessionVars["SELL_customincrement"])."','".$sessionVars["SELL_notimer"]."','".$sessionVars["SELL_promotion"]."','".$sessionVars["SELL_seats"]."','"."0"."')";
    
     $resbbb=mysql_query($queryaa);
    
  //   echo $queryaa;
    // echo "<BR><BR>";
   //   echo $queryrelist2;
    
    
    
    
    
    
}
       
			
		if ( 1 == 1 ) {
			// // Close auction
			$query = "UPDATE PHPAUCTIONXL_auctions SET closed='1',
			         starts='".$Auction[starts]."',
			         ends='".$Auction[ends]."',
			         sold=CASE sold WHEN 's' THEN 'y' ELSE sold END
			         WHERE
			         id=\"$Auction[id]\"";
			if (!mysql_query($query))
				errorLogSQL();
			printLogL($query, 1);
			
					$query = "UPDATE PHPAUCTIONXL_auctions2 SET closed='1'
			         WHERE
			         id=\"$Auction[id]\"";
			if (!mysql_query($query))
				errorLogSQL();
			printLogL($query, 1);
		}

		// //======================================================
		// WINNER PRESENT FEES NEED TO BE INSERTED
		// //======================================================
		if ($winner_present) {
			include $include_path.'endauction_winner.inc.php';
			if (count($WINNERS_NICK) > 0) {
				while (list($k, $v) = each($WINNERS_NICK)) {
					$Winner['name'] = $WINNERS_NAME[$k];
					$Winner['email'] = $WINNERS_EMAIL[$k];
					$Winner['nick'] = $WINNERS_NICK[$k];
					
					$Winner['quantity'] = $WINNERS_QUANT[$k];
					$Winner['wanted'] = $WINNERS_BIDQUANT[$k];
					// print $Winner['quantity']." - ".$Winner['wanted']."<BR>";
					// // ######################################################
					// // Send mail to the buyer
					
					
       $query435 = mysql_fetch_array(mysql_query("SELECT daily_wins FROM PHPAUCTIONXL_users WHERE nick='$Winner[nick]'"));
  
                  $beginner_wins = $query435['daily_wins'];
					
					          $beginner_wins++;
					          
					          
 $query34="UPDATE PHPAUCTIONXL_users SET daily_wins='$beginner_wins' WHERE nick='$Winner[nick]'";
 
 mysql_query($query34);
					

          $query = mysql_fetch_array(mysql_query("SELECT * FROM PHPAUCTIONXL_version_1_3 WHERE id='1'"));
  
   $admin_daily_win_limits = $query['daily_win_limits'];
 $admin_weekly_win_limits = $query['weekly_win_limits'];
   $admin_monthly_win_limits = $query['monthly_win_limits'];


		// CREATE WIN LIMIT DATES

    $daylimitdatestart = substr ($NOW, 0, 8);
    $daylimitdatestart .= "000000";
         // echo $daylimitdatestart."<BR>";

    $TIMEdaylimitdateend = mktime(date("H")+$SETTINGS['timecorrection'],date("i"),date("s"),date("m"), date("d")+1,date("Y"));

$NOWdaylimitdateend = date("YmdHis",$TIMEdaylimitdateend);

     $daylimitdateend = substr ($NOWdaylimitdateend, 0, 8);
    $daylimitdateend .= "000000";
          // echo $daylimitdateend."<BR>";
         $monthlylimitdatestart = substr ($NOW, 0, 6);
    $monthlylimitdatestart .= "01000000"; 
           // echo $monthlylimitdatestart."<BR>";
    
    $TIMEmonthlylimitdateend = mktime(date("H")+$SETTINGS['timecorrection'],date("i"),date("s"),date("m")+1, date("d"),date("Y"));

$NOWmonthlylimitdateend = date("YmdHis",$TIMEmonthlylimitdateend);

     $monthlylimitdateend = substr ($NOWmonthlylimitdateend, 0, 6);
    $monthlylimitdateend .= "01000000";
                    // echo $monthlylimitdateend."<BR>";
    $jd=cal_to_jd(CAL_GREGORIAN,date("m"),date("d"),date("Y"));
$text_day = (jddayofweek($jd,1));

          //   echo $text_day;
    if ( $text_day == "Monday" ) {
        $day_correct_backwards = -1;
        $day_correct_forwards = 6;
    }  
    if ( $text_day == "Tuesday" ) {
        $day_correct_backwards = -2;
        $day_correct_forwards =5;
    }
    if ( $text_day == "Wednesday" ) {
        $day_correct_backwards = -3;
        $day_correct_forwards = 4;
    }
        if ( $text_day == "Thursday" ) {
        $day_correct_backwards = -4;
        $day_correct_forwards = 3;
    }
    if ( $text_day == "Friday" ) {
        $day_correct_backwards = -5;
        $day_correct_forwards =2;
    }
    if ( $text_day == "Saturday" ) {
        $day_correct_backwards = -6;
        $day_correct_forwards =1;
    }
    if ( $text_day == "Sunday" ) {
        $day_correct_backwards = 0;
        $day_correct_forwards = 7;
    }
    
        //  echo $day_correct_backwards;
      //  echo $day_correct_forwards;
$TIMEweeklylimitdatestart = mktime(date("H")+$SETTINGS['timecorrection'],date("i"),date("s"),date("m"), date("d")+$day_correct_backwards,date("Y"));

$NOWweeklylimitdatestart = date("YmdHis",$TIMEweeklylimitdatestart);
    
        $weeklylimitdatestart = substr ($NOWweeklylimitdatestart, 0, 8);
    $weeklylimitdatestart .= "000000";

        // echo $weeklylimitdatestart."<BR>";
  
  $TIMEweeklylimitdateend = mktime(date("H")+$SETTINGS['timecorrection'],date("i"),date("s"),date("m"), date("d")+$day_correct_forwards,date("Y"));

$NOWweeklylimitdateend = date("YmdHis",$TIMEweeklylimitdateend);
    
        $weeklylimitdateend = substr ($NOWweeklylimitdateend, 0, 8);
    $weeklylimitdateend .= "000000";
    //echo $weeklylimitdateend."<BR>";

// Query Auctions For Limits  
  
  
   $querydaily = "select * from PHPAUCTIONXL_auctions
         WHERE current_high_bidder='$Winner[nick]' AND closed=1 AND
         ends > $daylimitdatestart AND
         ends < $daylimitdateend";
$resultdaily = mysql_query($querydaily);
$user_daily_wins = mysql_num_rows($resultdaily);
        $send = 0;
if ( $user_daily_wins <= $admin_daily_win_limits ) {
     $send = 1;
     include $include_path.'endauction_youwin.inc.php';
}

  if ( $user_daily_wins > $admin_daily_win_limits ) {
  
$query = "UPDATE PHPAUCTIONXL_auctions SET winlimit='1' 
				         WHERE
				         id=\"$Auction[id]\"";
				if (!mysql_query($query))
					errorLogSQL();
				printLogL($query, 1);

}
       
          $queryweekly = "select * from PHPAUCTIONXL_auctions
         WHERE current_high_bidder='$Winner[nick]' AND 
         closed=1 AND
         ends > $weeklylimitdatestart AND
         ends < $weeklylimitdateend";
$resultweekly = mysql_query($queryweekly);
$user_weekly_wins = mysql_num_rows($resultweekly);


if ( $user_weekly_wins <= $admin_weekly_win_limits ) {
    
     if ( $send == 0 ) {
             $send = 1;
    include $include_path.'endauction_youwin.inc.php';
    }
}

	
  if ( $user_weekly_wins > $admin_weekly_win_limits ) {
  
$query = "UPDATE PHPAUCTIONXL_auctions SET winlimit='2' 
				         WHERE
				         id=\"$Auction[id]\"";
				if (!mysql_query($query))
					errorLogSQL();
				printLogL($query, 1);

}
  			
				
				




     $querymonthly = "select * from PHPAUCTIONXL_auctions
         WHERE current_high_bidder='$Winner[nick]' AND 
         closed=1 AND
         ends > $monthlylimitdatestart AND
         ends < $monthlylimitdateend";
$resultmonthly= mysql_query($querymonthly);
$user_monthly_wins = mysql_num_rows($resultmonthly);


    if ( $user_monthly_wins <= $admin_monthly_win_limits ) {
         if ( $send == 0 ) {
             $send = 1;
        include $include_path.'endauction_youwin.inc.php';
              }
}			
					
	  if ( $user_monthly_wins > $admin_monthly_win_limits ) {
  
$query = "UPDATE PHPAUCTIONXL_auctions SET winlimit='3' 
				         WHERE
				         id=\"$Auction[id]\"";
				if (!mysql_query($query))
					errorLogSQL();
				printLogL($query, 1);

}				
					
					
					
					
					
					
					
				}
			}
			elseif (is_array($Winner)) {
				// // ######################################################
				// // Send mail to the buyer
				
       $query435 = mysql_fetch_array(mysql_query("SELECT daily_wins FROM PHPAUCTIONXL_users WHERE nick='$Winner[nick]'"));
  
                  $beginner_wins = $query435['daily_wins'];
					
					          $beginner_wins++;
					          
					          
 $query34="UPDATE PHPAUCTIONXL_users SET daily_wins='$beginner_wins' WHERE nick='$Winner[nick]'";
 
 mysql_query($query34);
					
					
					
					                 $query = mysql_fetch_array(mysql_query("SELECT * FROM PHPAUCTIONXL_version_1_3 WHERE id='1'"));
  
   $admin_daily_win_limits = $query['daily_win_limits'];
 $admin_weekly_win_limits = $query['weekly_win_limits'];
   $admin_monthly_win_limits = $query['monthly_win_limits'];


		// CREATE WIN LIMIT DATES

    $daylimitdatestart = substr ($NOW, 0, 8);
    $daylimitdatestart .= "000000";
         // echo $daylimitdatestart."<BR>";

    $TIMEdaylimitdateend = mktime(date("H")+$SETTINGS['timecorrection'],date("i"),date("s"),date("m"), date("d")+1,date("Y"));

$NOWdaylimitdateend = date("YmdHis",$TIMEdaylimitdateend);

     $daylimitdateend = substr ($NOWdaylimitdateend, 0, 8);
    $daylimitdateend .= "000000";
          // echo $daylimitdateend."<BR>";
         $monthlylimitdatestart = substr ($NOW, 0, 6);
    $monthlylimitdatestart .= "01000000"; 
           // echo $monthlylimitdatestart."<BR>";
    
    $TIMEmonthlylimitdateend = mktime(date("H")+$SETTINGS['timecorrection'],date("i"),date("s"),date("m")+1, date("d"),date("Y"));

$NOWmonthlylimitdateend = date("YmdHis",$TIMEmonthlylimitdateend);

     $monthlylimitdateend = substr ($NOWmonthlylimitdateend, 0, 6);
    $monthlylimitdateend .= "01000000";
                    // echo $monthlylimitdateend."<BR>";
    $jd=cal_to_jd(CAL_GREGORIAN,date("m"),date("d"),date("Y"));
$text_day = (jddayofweek($jd,1));

          //   echo $text_day;
    if ( $text_day == "Monday" ) {
        $day_correct_backwards = -1;
        $day_correct_forwards = 6;
    }  
    if ( $text_day == "Tuesday" ) {
        $day_correct_backwards = -2;
        $day_correct_forwards =5;
    }
    if ( $text_day == "Wednesday" ) {
        $day_correct_backwards = -3;
        $day_correct_forwards = 4;
    }
        if ( $text_day == "Thursday" ) {
        $day_correct_backwards = -4;
        $day_correct_forwards = 3;
    }
    if ( $text_day == "Friday" ) {
        $day_correct_backwards = -5;
        $day_correct_forwards =2;
    }
    if ( $text_day == "Saturday" ) {
        $day_correct_backwards = -6;
        $day_correct_forwards =1;
    }
    if ( $text_day == "Sunday" ) {
        $day_correct_backwards = 0;
        $day_correct_forwards = 7;
    }
    
        //  echo $day_correct_backwards;
      //  echo $day_correct_forwards;
$TIMEweeklylimitdatestart = mktime(date("H")+$SETTINGS['timecorrection'],date("i"),date("s"),date("m"), date("d")+$day_correct_backwards,date("Y"));

$NOWweeklylimitdatestart = date("YmdHis",$TIMEweeklylimitdatestart);
    
        $weeklylimitdatestart = substr ($NOWweeklylimitdatestart, 0, 8);
    $weeklylimitdatestart .= "000000";

        // echo $weeklylimitdatestart."<BR>";
  
  $TIMEweeklylimitdateend = mktime(date("H")+$SETTINGS['timecorrection'],date("i"),date("s"),date("m"), date("d")+$day_correct_forwards,date("Y"));

$NOWweeklylimitdateend = date("YmdHis",$TIMEweeklylimitdateend);
    
        $weeklylimitdateend = substr ($NOWweeklylimitdateend, 0, 8);
    $weeklylimitdateend .= "000000";
    //echo $weeklylimitdateend."<BR>";

// Query Auctions For Limits  
  
  
   $querydaily = "select * from PHPAUCTIONXL_auctions
         WHERE current_high_bidder='$Winner[nick]' AND closed=1 AND
         ends > $daylimitdatestart AND
         ends < $daylimitdateend";
$resultdaily = mysql_query($querydaily);
$user_daily_wins = mysql_num_rows($resultdaily);
        $send = 0;
if ( $user_daily_wins <= $admin_daily_win_limits ) {
     $send = 1;
     include $include_path.'endauction_youwin_nodutch.inc.php';
}

  if ( $user_daily_wins > $admin_daily_win_limits ) {
  
$query = "UPDATE PHPAUCTIONXL_auctions SET winlimit='1' 
				         WHERE
				         id=\"$Auction[id]\"";
				if (!mysql_query($query))
					errorLogSQL();
				printLogL($query, 1);

}
       
          $queryweekly = "select * from PHPAUCTIONXL_auctions
         WHERE current_high_bidder='$Winner[nick]' AND 
         closed=1 AND
         ends > $weeklylimitdatestart AND
         ends < $weeklylimitdateend";
$resultweekly = mysql_query($queryweekly);
$user_weekly_wins = mysql_num_rows($resultweekly);


if ( $user_weekly_wins <= $admin_weekly_win_limits ) {
    
     if ( $send == 0 ) {
             $send = 1;
    include $include_path.'endauction_youwin_nodutch.inc.php';
    }
}

	
  if ( $user_weekly_wins > $admin_weekly_win_limits ) {
  
$query = "UPDATE PHPAUCTIONXL_auctions SET winlimit='2' 
				         WHERE
				         id=\"$Auction[id]\"";
				if (!mysql_query($query))
					errorLogSQL();
				printLogL($query, 1);

}
  			
				
				




     $querymonthly = "select * from PHPAUCTIONXL_auctions
         WHERE current_high_bidder='$Winner[nick]' AND 
         closed=1 AND
         ends > $monthlylimitdatestart AND
         ends < $monthlylimitdateend";
$resultmonthly= mysql_query($querymonthly);
$user_monthly_wins = mysql_num_rows($resultmonthly);


    if ( $user_monthly_wins <= $admin_monthly_win_limits ) {
         if ( $send == 0 ) {
             $send = 1;
        include $include_path.'endauction_youwin_nodutch.inc.php';
              }
}			
					
	  if ( $user_monthly_wins > $admin_monthly_win_limits ) {
  
$query = "UPDATE PHPAUCTIONXL_auctions SET winlimit='3' 
				         WHERE
				         id=\"$Auction[id]\"";
				if (!mysql_query($query))
					errorLogSQL();
				printLogL($query, 1);

}				
				
	
				
				
			}
		}
		if (!$winner_present) {
			// // ######################################################
			// // Send mail to the seller if no winner
			if($Seller['endemailmode']!='cum'){
				include $include_path.'endauction_nowinner.inc.php';
			}else{
				#// Save in the database to send later
				@mysql_query("INSERT INTO PHPAUCTIONXL_pendingnotif VALUES (
								NULL,
								".$Auction['id'].",
								".$Seller['id'].",
								'',
								'".serialize($Auction)."',
								'".serialize($Seller)."',
								'".date("Ymd")."')");
			}
		}
	}
	foreach($categories as $cat_id=>$category) {
		if($category['updated']) {
			$query = "UPDATE PHPAUCTIONXL_categories SET
			         counter=$category[counter],
			         sub_counter=$category[sub_counter]
			         WHERE cat_id=$cat_id";
			$res = mysql_query($query);
			$category['updated']=false;
		}
	}
}

/**
* "remove" old auctions (archive them)
*/
printLog("\n");
printLog("++++++ Archiving old auctions");

$expireAuction = 60 * 60 * 24 * $SETTINGS[archiveafter]; // time of auction expiration (in seconds)
$expiredTime = date ("YmdHis", $TIME - $expireAuction);

$query = "SELECT * FROM PHPAUCTIONXL_auctions WHERE ends<='$expiredTime'";

printLog($query);
$result = mysql_query($query);
if ($result) {
	$num = mysql_num_rows($result);
	printLog($num . " auctions to archive");
	if ($num > 0) {
		$resultCLOSEDAUCTIONS = $result;
		while ($row = mysql_fetch_array($resultCLOSEDAUCTIONS, MYSQL_ASSOC)) {
			$AuctionInfo = $row;
			printLogL("Processing auction: " . $AuctionInfo['id'], 0);

			/**
			* ? this auction
			*/
			$query = "DELETE FROM PHPAUCTIONXL_auctions WHERE id='" . $AuctionInfo['id'] . "'";
			if (!mysql_query($query))
				errorLogSQL();
          	$query22 = "DELETE FROM PHPAUCTIONXL_auctions WHERE id='" . $AuctionInfo['id'] . "'";
			if (!mysql_query($query22))
				errorLogSQL();
			/**
			* delete bids for this auction
			*/
			$query = "SELECT * FROM PHPAUCTIONXL_bids WHERE auction='" . $AuctionInfo['id'] . "'";
			$result = mysql_query($query);
			if ($result) {
				$num = mysql_num_rows($result);
				if ($num > 0) {
					printLogL ($num . " bids for this auction to delete", 1);
					$resultBIDS = $result;
					while ($row = mysql_fetch_array($resultBIDS, MYSQL_ASSOC)) {
						/**
						* archive this bid
						*/
						$query = "delete from PHPAUCTIONXL_bids where auction='" . $row['auction'] . "'";
						$res = mysql_query($query);
						if (!$res)
							errorLogSQL();
					}
				}
			} else
				errorLogSQL();
			// // #################################################################################################
			// // Gian - Added setp 14 2002
			// // Delete proxybid entries
			@mysql_query("delete from PHPAUCTIONXL_proxybid WHERE itemid=".$AuctionInfo['id']);
			// // Delete counter entries
			@mysql_query("delete from PHPAUCTIONXL_auccounter WHERE auction_id=".$AuctionInfo['id']);
			// // Delete variants entries
			// // Pictures gallery
			if (file_exists($image_upload_path . "$AuctionInfo[id]")) {
				if ($dir = @opendir($image_upload_path .$AuctionInfo['id'])) {
					while ($file = readdir($dir)) {
						if ($file != "." && $file != "..") {
							@unlink($image_upload_path .$AuctionInfo['id']."/" . $file);
						}
					}
					closedir($dir);

					@rmdir($image_upload_path .$AuctionInfo['id']);
				}
			}
			// // Picture
			@unlink($image_upload_path . $AuctionInfo['pict_url']);
		}
	}
}
else {
	errorLogSQL();
}
// ***** control if there are some suspended auction and see if now user can pay fee ****///
if ($SETTINGS[feetype] == "prepay") {
	$auctione = mysql_query("SELECT * FROM PHPAUCTIONXL_auctions WHERE ends<='$NOW' AND closed='-1'");
	while ($auction_result = mysql_fetch_array($auctione)) {
		// echo  $auction_result["user"];
		/**
		* ********************************************** retrieve seller info ************************************
		*/
		$query = "SELECT * FROM PHPAUCTIONXL_users WHERE id='" . $auction_result["user"] . "'";
		printLogL($query, 1);
		$result = mysql_query ($query);
		if ($result) {
			if (mysql_num_rows($result) > 0) {
				mysql_data_seek ($result, 0);
				$Seller = mysql_fetch_array($result);
			} else
				$Seller = array();
		} else
			errorLogSQL();

		/**
		* -***************************************** retrieve buyer info ***************************************
		*/
		$query = "SELECT * FROM PHPAUCTIONXL_bids WHERE auction='" . $auction_result['id'] . "' ORDER BY bid DESC";
		printLogL($query, 1);
		$result = mysql_query ($query);
		if ($result) {
			if (mysql_num_rows($result) > 0 and ($auction_result['current_bid'] > $auction_result['reserve_price'])) {
				$decrem = mysql_num_rows($result);
				mysql_data_seek($result, 0);
				$WinnerBid = mysql_fetch_array($result);
				$winner_present = true;

				/**
				* get winner info
				*/
				$query = "SELECT * FROM PHPAUCTIONXL_users WHERE nick='" . $WinnerBid['current_high_bidder'] . "'";
				$result = mysql_query ($query);
				if ($result) {
					if (mysql_num_rows($result) > 0) {
						mysql_data_seek ($result, 0);
						$Winner = mysql_fetch_array($result);
					} else
						$Winner = array ();
				} else
					errorLogSQL();
			}
		}

		$balance = true;
		$finalfee = 0;
		/**
		* *********************************get the fee*******************************************
		*/
		// // Mail seller
		
		include $include_path.'endauction_winner.inc.php';
		if ($winner_present) {
			printLogL ("mail to winner: " . $Winner["email"], 1);
			
			include $include_path.'endauction_youwin.inc.php';
		}
	}
}
/*
* Purging thumbnails cache and not more used images

if(!file_exists($image_upload_path."cache"))
	mkdir($image_upload_path."cache",0777);
if(!file_exists($image_upload_path."cache/purge"))
	@touch($image_upload_path."cache/purge");
$purggecachetime=filectime($image_upload_path."cache/purge");
if((time()-$purgecachetime)>86400) {
	$dir=$image_upload_path."cache";
	if ($dh = opendir($dir)) {
		while (($file = readdir($dh)) !== false) {
			if($file!="purge" && !is_dir("$dir/$file") && (time()-filectime("$dir/$file"))>86400)
				@unlink("$dir/$file");
		}
		closedir($dh);
	}
	// starting all site images purge
	$imgarray[]=$SETTINGS['logo'];
	$imgarray[]=$SETTINGS['background'];
	$result = mysql_query("SELECT pict_url from PHPAUCTIONXL_auctions where photo_uploaded='1'");
	while($row=mysql_fetch_array($result, MYSQL_NUM))
		$imgarray[]=$row[0];
	$result = mysql_query("SELECT id from PHPAUCTIONXL_auctions");
	$imgdir=array();
	while($row=mysql_fetch_array($result, MYSQL_NUM)) {
		if(is_dir($uploaded_path.$row[0]))
			$imgdir[]=$row[0];
	}
	//Ordinary images purge
	$dir=$image_upload_path;
	if ($dh = opendir($dir)) {
		while (($file = readdir($dh)) !== false) {
			if($file!="purge" &&
			        !is_dir($dir.$file) &&
			        (time()-filectime($dir.$file))>86400 &&
			        !in_array($file,$imgarray))
				unlink($dir.$file);
		}
		closedir($dh);
	}
	//galleries dirs and files purge
	if (is_array($imgdir) && ($dh = opendir($dir))) {
		while (($file = readdir($dh)) !== false) {
			if($file!="banners" &&
			        $file!=".." &&
			        $file!="." &&
			        is_dir("$dir.$file") &&
			        (time()-filectime($dir.$file))>86400 &&
			        !in_array($file,$imgdir))
				$ddel=$dir.$file;
			if ($ddh = @opendir($ddel)) {
				while (($fdel = readdir($ddh)) !== false) {
					if(!is_dir("$ddel/$fdel"))
						unlink("$ddel/$fdel");
				}
				closedir($ddh);
				rmdir($ddel);
			}
		}
		closedir($dh);
	}
	//Banners purge
	$result = mysql_query("SELECT name from PHPAUCTIONXL_banners");
	while($row=mysql_fetch_array($result, MYSQL_NUM)) {
		$imgarray[]="banners/".$result[0];
	}
	$dir=$image_upload_path."banners/";
	if(is_dir($dir)) {
		if ($dh = opendir($dir)) {
			while (($file = readdir($dh)) !== false) {
				if($file!="purge" &&
				        !is_dir($dir.$file) &&
				        (time()-filectime($dir.$file))>86400 &&
				        !in_array("banners/".$file,$imgarray))
					unlink($dir.$file);
			}
			closedir($dh);
		}
	}
	@touch($image_upload_path."cache/purge");
} */

#// Handle Wanted Items
@mysql_query("UPDATE PHPAUCTIONXL_wanted SET closed='1' WHERE ends <='$NOW'");
$expireAuction = 60 * 60 * 24 * $SETTINGS[archiveafter]; // time of auction expiration (in seconds)
$expiredTime = date ("YmdHis", $TIME - $expireAuction);
@mysql_query("DELETE FROM PHPAUCTIONXL_wanted WHERE ends<='$expiredTime'");

// // Update counters
include $include_path."updatecounters.inc.php";

// finish cron script
printLog ("=========================== ENDING CRON: ". date("F d, Y H:i:s"));
closeLogFile();

     mysql_close($linktodatabase);



?>
